import { drizzle } from "drizzle-orm/mysql2";
import type { AnyMySql2Connection, MySql2Database } from "drizzle-orm/mysql2";
import * as Schema from "./schema.ts";

type Drizzle = MySql2Database & { $client: AnyMySql2Connection };

let dataBases: {
  [index: string]: Drizzle;
} = {};

type ConnectionConfig = {
  /** 数据库连接地址 */
  uri?: string;
};

type ConnectConfig = {
  /** 连接名称 */
  name?: string;
  /** 是否记录日志 */
  logger?: boolean;
  /** 数据库表模式 */
  casing?: "camel" | "snake_case" | "pascal" | "none";
  /** 数据库连接配置 */
  connection: ConnectionConfig;
  schema?: any;
};

/**
 * 连接数据库
 * @param {string|ConnectConfig} config -- 连接配置, eg: mysql://x:x@localhost/x
 */
export function connect(config: string | ConnectConfig) {
  if (typeof config === "string") {
    dataBases["default"] = drizzle({
      connection: { uri: config },
      logger: true,
      casing: "snake_case",
    });
  } else {
    const name = config.name || "default";
    delete config.name;
    dataBases[name] = drizzle({
      logger: true,
      casing: "snake_case",
      schema: Schema,
      mode: "default",
      ...config,
    } as any);
  }
}

/**
 * 获取数据库实例
 * @param name - 连接名称
 */
export function db(name = "default"): Drizzle {
  return dataBases[name || "default"];
}

/**
 * 关闭数据库连接
 * @param name - 连接名称
 */
export function close(name = "default") {
  if (name in dataBases) {
    dataBases[name].$client.end();
    delete dataBases[name];
  }
}

/**
 * 销毁所有数据库连接
 */
export function destroy() {
  for (const name in dataBases) {
    close(name);
  }
  dataBases = {};
}
